# @Time    : 2021/1/11 3:11 下午
# @Author  : Youyandong
# @File    : utils.py
# @Software: PyCharm
# @use: 自定义后端认证
from django.contrib.auth.backends import ModelBackend
import re
from users.models import User


def get_user_by_account(account):
    """
    @param account:  用户名或手机号
    @return: user
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            # 手机号
            user = User.objects.get(mobile=account)
        else:
            # 用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user
    

class UsernameModelBackend(ModelBackend):
    # 重写用户认证方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        @param request:
        @param username: 用户名或手机号
        @param password: 密码
        @param kwargs: 额外参数
        @return: user
        """
        # 查询用户
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None


